package org.dllwh.mongodb;

import jakarta.annotation.Resource;
import org.dllwh.mongodb.model.SysUser;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;

/**
 * 把今天最好的表现当作明天最新的起点．．～
 * <p>
 * Today the best performance as tomorrow the newest starter!
 *
 * @ClassName FindTest
 * @Description MongoTemplate 查询操作测试类
 * @Author: <a href="mailto:duleilewuhen@sina.com">独泪了无痕</a>
 * @Date 2025-05-10 00:48
 * @版本 V 1.0.1
 * @since JDK 17
 */
@SpringBootTest
public class FindTest {
    @Resource
    private MongoTemplate mongoTemplate;
    private final String collectionName = "FindTest";

    @BeforeEach
    public void init() {
        // 删除集合
        mongoTemplate.dropCollection(collectionName);
        List<SysUser> userList = new ArrayList<>();
        userList.add(new SysUser("1", "白鹿", "女", 31));
        userList.add(new SysUser("2", "陈都灵", "女", 32));
        userList.add(new SysUser("3", "高圆圆", "女", 46));
        userList.add(new SysUser("4", "张含韵", "女", 36));
        userList.add(new SysUser("5", "李沁", "女", 35));
        userList.add(new SysUser("6", "胡歌", "男", 43));
        userList.add(new SysUser("7", "刘亦菲", "女", 38));
        userList.add(new SysUser("8", "成龙", "男", 71));
        userList.add(new SysUser("9", "杨幂", "男", 39));
        userList.add(new SysUser("10", "陈钰琪", "女", 33));
        mongoTemplate.insert(userList, collectionName);
    }

    /**
     * 根据条件查询集合中符合条件的文档
     */
    @Test
    public void findTest() {
        Query query = new Query(Criteria.where("age").gte(30).lte(40));
        mongoTemplate.find(query, SysUser.class, collectionName).forEach(System.out::println);
    }

    /**
     * 根据条件查询集合中符合条件的文档，返回第一条数据
     */
    @Test
    public void findOneTest() {
        Query query = new Query(Criteria.where("gender").is("女"));
        SysUser sysUser = mongoTemplate.findOne(query, SysUser.class, collectionName);
        System.out.println("查询结果：" + sysUser);
    }

    /**
     * 查询集合中指定的ID文档数据
     */
    @Test
    public void findByIdTest() {
        SysUser sysUser = mongoTemplate.findById("1", SysUser.class, collectionName);
        System.out.println(sysUser);
    }

    /**
     * 查询集合中的全部文档数据
     */
    @Test
    public void findAllTest() {
        mongoTemplate.findAll(SysUser.class, collectionName).forEach(System.out::println);
    }

    @Test
    public void countTest() {
        System.out.println( mongoTemplate.count(new Query(), collectionName));
    }
}
